package servlet;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.PetDao;
import dao.PetDaoImpl;
import entity.Pet;

@WebServlet("/pet")
public class PetServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private PetDao petDao = new PetDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); // 设置请求编码
        response.setContentType("text/html; charset=UTF-8"); // 设置响应编码

        String action = request.getParameter("action");
        if ("findAll".equals(action)) {
            handleFindAll(request, response);
        } else if ("findByBreed".equals(action)) {
            handleFindByBreed(request, response);
        }
    }

    private void handleFindAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Pet> pets = petDao.findAll();
        request.setAttribute("pets", pets);
        request.getRequestDispatcher("/WEB-INF/views/petList.jsp").forward(request, response);
    }

    private void handleFindByBreed(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int breed = Integer.parseInt(request.getParameter("breed"));
        List<Pet> pets = petDao.findByBreed(breed);
        request.setAttribute("pets", pets);
        request.getRequestDispatcher("/WEB-INF/views/petList.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
